<?php
declare(strict_types=1);

namespace app\index\controller\api;

use \Swoole\Http\Request;
use \Swoole\Http\Response;
use sys\Log;

class Accounts
{
    public \lib\User $user;
    public \lib\Merchant $merchant;
    public $middleware = [
        \lib\middleware\NetbarAuth::class=>[]
    ];

    public function unique(Request $request)
    {
        $data = json_decode($request->getContent(), true);
        $checker = validate([
            'type'=>'require',
            'value'=>'require'
        ], __LINE__.'.'.__CLASS__)->check($data);

        if(!$checker->pass()) return $checker->jsonSerialize();

        $message='唯一验证没通过';
        switch($data['type'])
        {
            case 'wanjia.username':
                $tbl = 'el_user';
                $opt = [
                    ['username','=', $data['value']]
                ];
                if(!empty($data['id']))
                    $opt[] = ['id', '<>', $data['id']];
                $message = '相同登录名账户已经存在.';
            break;
            default:
                return ['success'=>false,'message'=>'不支持的验证规则'];
        }

        $db = new \sys\Db();
        $retv = ['success'=> $db->table($tbl)->where($opt)->field('id')->find() ? false : true];
        if($retv['success'] == false) $retv['message'] = $message;

        return $retv;
    }

    public function read(Request $request, Response $response)
    {
        $role_id = $this->user->role_id;
        $mid     = $this->merchant->id;

        $opt = [['el_user_role.mid', '=', $mid]];

        switch($role_id){
            case 1: // 系统管理员
                break;
            case 2: //店长
                $opt[] = ['el_user_role.role_id' , '<>', 1];
                break;
            case 3: //收银员
                $opt[] = ['el_user_role.role_id' , 'NOT IN', [1,2]];
                break;
        }

        $db = new \sys\Db();
        $data =  $db->table('el_user_role')
                    ->join('tp_user', 'tp_user.id = el_user_role.uid')
                    ->where($opt)
                    ->field([
                        'tp_user.id',
                        'tp_user.username',
                        'el_user_role.szDisplayName as realname',
                        'IDNO',
                        'el_user_role.role_id',
                        'el_user_role.mid',
                        'el_user_role.createtime',
                        'el_user_role.freeze',
                        'el_user_role.roles'
                    ])
                    ->order('role_id ASC, el_user_role.createtime DESC')
                    ->select() ?? [];

        return ['success'=>true, 'data'=>$data];
    }

    public function create(Request $request, Response $response)
    {
        $role_id = $this->user->role_id;
        $mid     = $this->merchant->id;

        $post = json_decode($request->getContent(), true);
        $checker = validate([
            'id'=>'integer',
            'role_id'=>'require|integer|in:1,2,3',
            'username'=>'require|length:3,32|nospace',
            'realname'=>'require|chs|length:1,20|nospace',
            'tel'=>'require|mobile|nospace',
            'password'=>'ens|length:6,32|nospace',
            'frozen'=>'require|in:0,1'
        ], __LINE__.'.'.__CLASS__)->check($post);

        if(!$checker->pass()) return $checker->jsonSerialize();

        $db = new \sys\Db();
        $map = ['realname'=>'szDisplayName','tel'=>'szTel','role_id'=>'role_id','frozen'=>'frozen'];
        if(isset($post['id'])){
            if(isset($post['password'])){
                if(0== strlen(trim($post['password']))){
                    unset($post['password']);
                }else{
                    if(1 == $db->execute("SELECT PASSWORD(?) AS `pwd`", [[$post['password'], \PDO::PARAM_STR]], \sys\Db::SQL_FIND)){
                        $post['password']  = $db->result(['pwd'=>'string'], \sys\Db::SQL_FIND)['pwd'];
                    }
                }
            }

            $user = $db->table('tp_user')->where([['id','=', $post['id']]])->find();
            if(null === ($role = $db->table('el_user_role')->where([['uid','=', $user['id']], ['mid','=', $mid]])->find())){
                return ['success'=>false, 'message'=>'这个用户不是你商家的工作人员.'];
            }

            switch($role_id){
                case 1:
                    if($this->user->id == $user['id'])
                        unset($post['role_id']);
                break;
                case 2:
                    if($role['role_id'] == 1)
                        return ['success'=>false, 'message'=>'无权限!, 店长不允许修改老板资料.'];

                    if($role['role_id'] ==2 && $user['id'] != $this->user->id)
                        return ['success'=>false, 'message'=>'只有老板才能修其它改店长资料.'];

                    if($role['role_id'] != $post['role_id']) 
                        return ['success'=>false, 'message'=>'只有老板才能修改用户角色.'];

                    break;
                case 3:
                    if($this->user->id != $user['id']) return ['success'=>false,'message'=>'收银员只能改自己的账户资料.'];
                    if($role['role_id'] != $post['role_id']) return ['success'=>false, 'message'=>'只有老板才能修改用户角色.'];
                    break;
            }

            foreach($map as $from=>$to){
                if(isset($post[ $from ])){
                    if(is_array($post[$from])){
                        if(!array_compare($post[ $from ], $role[ $to ] ?? [])){
                            $update[ $to ] = $post[ $from ];
                        }
                    }elseif(!isset($post[$from]) || $role[$to] !== $post[$from]){
                        $update[$to] = $post[$from];
                    }
                }
            }

            if(isset($update)){
                $db->table('el_user_role')->where([['id','=', $role['id']]])->update($update);
            }

            if(isset($post['password'])){
                $db->table('tp_user')->where([['id','=', $user['id']]])->update(['password'=>$post['password']]);
            }

            return ['success'=>true, 'message'=>'修改成功'];

        }else{
            if($db->table('tp_user')->where([['username','=', $post['username']]])->field('id')->find()){
                return ['success'=>false, 'message'=>'该账号不能使用.'];
            }

            switch($role_id) {
            case 3:
                return ['success'=>false, 'message'=>'收银员不能创建账户.'];
                break;
            case 2:
                if($post['role_id'] != 2)  ['success'=>false, 'message'=>'店长只允许创建收银员账户.'];
                break;
            case 1:
                if($post['role_id'] == 1) return ['success'=>false, 'message'=>'老板账户只能有一个.'];
                break;
            }

            if(!isset($post['password'])) return ['success'=>false, 'message'=>'密码必须.'];

            if(1 == $db->execute("SELECT PASSWORD(?) AS `pwd`", [[$post['password'], \PDO::PARAM_STR]], \sys\Db::SQL_FIND)){
                $post['password']  = $db->result(['pwd'=>'string'], \sys\Db::SQL_FIND)['pwd'];
            }

            $time = time();
            $db->startTrans();
            try{
                $user_id = $db->table('tp_user')->insert([
                    'mid'           => 0,
                    'username'      =>$post['username'],
                    'realname'      =>$post['realname'],
                    'password'      =>$post['password'],
                    'tel'           =>$post['tel'],
                    'createtime'    =>$time
                ]);
                
                $role = $db->table('el_user_role')->insert([
                    'uid'           =>$user_id,
                    'mid'           =>$mid,
                    'role_id'       =>$post['role_id'],
                    'szDisplayName' =>$post['realname'],
                    'szTel'         =>$post['tel'],
                    'roles'         =>[],
                    'createtime'    =>$time
                ]);

                $db->commit();
                return ['success'=>true, 'message'=>'创建账户成功'];
            }catch(\Throwable $e){
                $db->rollback();
                Log::write($e->getMessage()."\n".$e->getTraceAsString(),'ERROR');
            }

            return ['success'=>false, 'message'=>'创建账户失败'];
        }

    }

    public function destroy(Request $request, Response $response)
    {
        $user_id = $this->user->id;
        $role_id = $this->user->role_id;
        $mid     = $this->merchant->id;

        $post = json_decode($request->getContent(), true);
        $checker = validate([
            'id'=>'require|integer',
        ], __LINE__.'.'.__CLASS__)->check($post);

        if(!$checker->pass()) return $checker->jsonSerialize();

        if($post['id'] == $user_id)
            return  ['success'=>false,'message'=>'不能删除自己.'];
        
        if($role_id == 3)
            return  ['success'=>false,'message'=>'没有权限.'];
        
        $db = new \sys\Db();
        if(null === ($role = $db->table('el_user_role')->where([['uid','=', $post['id']], ['mid','=', $mid]])->find())){
            return ['success'=>false, 'message'=>'这个用户不是你商家的工作人员.'];
        }

        if($role['role_id'] == 1)
            return ['success'=>false,'message'=>'老板账号不能删除.'];

        if($role_id == 2 && $role['role_id'] != 3){
            return ['success'=>false,'message'=>'没有权限.'];
        }

        if(null !== ($user = $db->table('tp_user')->where([['id','=', $post['id']]])->field(['id', 'mid', 'IDNO','amount', 'frozen_amount'])->find())){
            if(empty($user['IDNO']) && ($user['amount'] - $user['frozen_amount']) == 0 && $user['mid'] === 0){
                $db->table('tp_user')->where([['id','=', $user['id']]])->limit(1)->delete();
            }
        }

        $db->table('el_user_role')->where([['id','=', $role['id']]])->limit(1)->delete();
        
        return ['success'=>true,'message'=>'删除成功.'];
    }
}